package com.yanx.system.web.infra.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.yanx.common.command.executor.QueryExecutor;
import com.yanx.common.security.SecurityUtils;
import com.yanx.system.base.domain.entity.QSysDept;
import com.yanx.system.base.domain.entity.QSysUser;
import com.yanx.system.base.domain.entity.SysUser;
import com.yanx.system.base.domain.entity.rel.QSysRoleDept;
import com.yanx.system.base.model.vo.SysRoleVo;
import com.yanx.system.web.query.SysRoleByRoleKeyQry;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gotanks
 * @create 2023/6/5
 */
public class DataScopeUtil {
    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    private static final QueryExecutor queryExecutor = SpringUtil.getBean(QueryExecutor.class);

    protected static final JPAQueryFactory queryFactory = SpringUtil.getBean(JPAQueryFactory.class);

    public static BooleanBuilder getUserScopeCondition() {
        return getScopeCondition(true);
    }

    public static BooleanBuilder getDeptScopeCondition() {
        return getScopeCondition(false);
    }

    private static BooleanBuilder getScopeCondition(boolean isUser) {
        QSysUser sysUser = QSysUser.sysUser;
        QSysDept sysDept = QSysDept.sysDept;
        QSysRoleDept sysRoleDept = QSysRoleDept.sysRoleDept;
        BooleanBuilder condition = new BooleanBuilder();
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null && !SysUser.isAdmin(loginUser.getUserId())) {
            Long deptId = loginUser.get("deptId");
            List<String> conditions = new ArrayList<String>();
            for (String roleKey : loginUser.getRoles()) {
                SysRoleVo role = queryExecutor.execute(new SysRoleByRoleKeyQry(roleKey));

                String dataScope = role.getDataScope();
                if (!DATA_SCOPE_CUSTOM.equals(dataScope) && conditions.contains(dataScope)) {
                    continue;
                }
//                if (StringUtils.isNotEmpty(permission) && StringUtils.isNotEmpty(role.getPermissions())
//                        && !StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission))) {
//                    continue;
//                }
                if (DATA_SCOPE_ALL.equals(dataScope)) {
                    break;
                } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
                    condition.or(sysDept.id.in(
                            queryFactory.select(sysRoleDept.deptId).from(sysRoleDept).where(sysRoleDept.roleId.eq(role.getId()))
                    ));
//                    sqlString.append(StringUtils.format(
//                            " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias,
//                            role.getRoleId()));
                } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
                    condition.or(sysDept.id.eq(deptId));
//                    sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
                } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                    condition.or(sysDept.id.in(
                            queryFactory.select(sysDept.id).from(sysDept).where(
                                    sysDept.id.eq(deptId).
                                            or(Expressions.booleanTemplate("find_in_set({0}, {1}) > 0", deptId, sysDept.ancestors))
                            )
                    ));
//                    sqlString.append(StringUtils.format(
//                            " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
//                            deptAlias, user.getDeptId(), user.getDeptId()));
                } else if (DATA_SCOPE_SELF.equals(dataScope)) {
                    if (isUser) {
                        condition.or(sysUser.id.eq(loginUser.getUserId()));
                    } else {
                        condition.or(sysDept.id.eq(0L));
                    }
//                    if (StringUtils.isNotBlank(userAlias)) {
//                        sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
//                    } else {
//                        // 数据权限为仅本人且没有userAlias别名不查询任何数据
//                        sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
//                    }
                }
                conditions.add(dataScope);
            }


//            // 如果是超级管理员，则不过滤数据
//            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
//                String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), PermissionContextHolder.getContext());
//                dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
//                        controllerDataScope.userAlias(), permission);
//            }
        }
        return condition;
    }
}
